class DataStorage {
  /**
   * 通用缓存方法
   * @param {String} name:缓存名
   * @param {String} type:类型。local:localStorage  session:SessionStorage
   * @param {Number} count:保存最大数量，0:无限制
   * @param {Boolean} distinct:是否去重
   * @param {String} distinctKey:唯一值key
   */
  constructor(options) {
    const defaultConfig = {
      type: 'local',
      count: 10,
      distinct: true,
      distinctKey: 'personnel_no'
    }
    this.options = Object.assign({}, defaultConfig, options)
  }
  /**
   * 获取缓存
   * @returns 缓存
   */
  getStorage() {
    const { type, name } = this.options
    if (type === 'local') {
      const items = localStorage.getItem(name)
      return items ? JSON.parse(items) : []
    } else if (type === 'session') {
      const items = sessionStorage.getItem(name)
      return items ? JSON.parse(items) : []
    } else {
      console.warn('请输入正确的类型')
    }
  }
  /**
   * 设置缓存
   * @param {Array} value
   * @returns
   */
  setStorage(value) {
    const {
      type,
      name,
      count,
      distinct,
      distinctKey
    } = this.options
    let items = this.getStorage()
    if (distinct) {
      items = items.filter(i => {
        return !value.some(ii => ii[distinctKey] === i[distinctKey])
      })
    }
    items.push(...value)
    // 判断是否超过最大长度
    if (count && items.length > count) {
      items = items.slice(items.length - count)
    }
    if (type === 'local') {
      return localStorage.setItem(name, JSON.stringify(items))
    } else if (type === 'session') {
      return sessionStorage.setItem(name, JSON.stringify(items))
    } else {
      console.warn('请输入正确的类型')
    }
  }
}

export default DataStorage
